package org.example.aienglishapp.util.oss;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;


@RestController
@RequestMapping("/api/oss")
public class OssController {

    @Autowired
    private OssService ossService;

    /**
     * 上传文件
     * @param file 上传的文件
     * @return 文件在 OSS 中的 URL
     */
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        String fileUrl = ossService.uploadFile(file);
        return ResponseEntity.ok(fileUrl);
    }

    /**
     * 下载文件
     * @param objectName 文件在 OSS 中的对象名称
     * @param response 响应对象
     * @throws IOException IO 异常
     */
    @GetMapping("/download/{objectName}")
    public void downloadFile(@PathVariable String objectName, HttpServletResponse response) throws IOException {
        // 打印接收到的 objectName
        System.out.println("Received objectName: " + objectName);

        // 拼接完整的对象键
        String fullObjectName = "standard/" + objectName;

        // 获取文件输入流
        InputStream inputStream = ossService.downloadFile(fullObjectName);

        if (inputStream == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
            return;
        }

        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + objectName + "\"");

        // 读取文件并写入响应输出流
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            response.getOutputStream().write(buffer, 0, bytesRead);
        }
        inputStream.close();
    }
}